﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using System.Collections.ObjectModel;
using CSP.Model.CSP;
using CSP.Model.CSPEnum;
using System.Collections;

namespace CSP.Web.MyHome.ServiceInfo
{
    public partial class Add : CSPMyHome
    {
        private string _currentURL = "";

        /// <summary>
        /// 当前的url路径
        /// </summary>
        protected string CurrentURL
        {
            get
            {
                return _currentURL;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _currentURL = Server.UrlEncode(Request.Url.OriginalString);
            if (!IsPostBack)
            {
                this.L_ServiceType.InnerText = this.Server.UrlDecode(Request["InfoType"].Split(',')[2].Split('|')[0]);
                InitControl();
            }
        }

        private void InitControl()
        {
            BindAddressUI();
            BindOriginalPriceUnitUI();
            BindPriceUnitUI();
            BindClassTypeUI();
            //Dictionary<int, string> imageUrls = new Dictionary<int, string>();
            //imageUrls.Add(1, "/Upload/Tmp/image/20120906/201296009734.jpg");
            //imageUrls.Add(2, "/Upload/Tmp/image/20120906/201296009734.jpg");
            //this.U_ImageUpload.SetImageURL = imageUrls;
        }



        private void BindAddressUI()
        {
            this.R_Address.DataSource = GetServiceAreaByUser();
            this.R_Address.DataTextField = "name";
            this.R_Address.DataValueField = "id";
            this.R_Address.DataBind();
            if (this.R_Address.Items.Count != 0)
            {
                this.R_Address.Items[0].Selected = true;
            }
        }

        private void BindOriginalPriceUnitUI()
        {
            this.S_OriginalPriceUnit.DataSource = GetPriceUnit();
            this.S_OriginalPriceUnit.DataTextField = "name";
            this.S_OriginalPriceUnit.DataValueField = "id";
            this.S_OriginalPriceUnit.DataBind();
        }

        private void BindPriceUnitUI()
        {
            this.S_PriceUnit.DataSource = GetPriceUnit();
            this.S_PriceUnit.DataTextField = "name";
            this.S_PriceUnit.DataValueField = "id";
            this.S_PriceUnit.DataBind();
        }

        private void BindClassTypeUI()
        {
            this.S_ClassType.DataSource = GetClassType();
            this.S_ClassType.DataTextField = "name";
            this.S_ClassType.DataValueField = "id";
            this.S_ClassType.DataBind();
        }

        /// <summary>
        /// 根据当前用户获取地理位置
        /// </summary>
        private ICollection<CSP.Model.CSP.Address> GetServiceAreaByUser()
        {
            ICollection<CSP.Model.CSP.Address> addresses = new Collection<CSP.Model.CSP.Address>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IAddressBll addressBll = bllFactory.GetAddressBll())
            {
                addresses = addressBll.FindByUser(UserProvider.UserName);
            }
            return addresses;
        }

        /// <summary>
        /// 获取价格单位
        /// </summary>
        /// <returns></returns>
        private ICollection<PriceUnit> GetPriceUnit()
        {
            ICollection<PriceUnit> priceUnits = new Collection<PriceUnit>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IPriceUnitBll priceUnitBll = bllFactory.GetPriceUnitBll())
            {
                priceUnits = priceUnitBll.FindAll();
            }
            return priceUnits;
        }

        /// <summary>
        /// 获取开课方式
        /// </summary>
        /// <returns></returns>
        private ICollection<ClassType> GetClassType()
        {
            ICollection<ClassType> classTypes = new Collection<ClassType>();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IClassTypeBll classTypeBll = bllFactory.GetClassTypeBll())
            {
                classTypes = classTypeBll.FindAll();
            }
            return classTypes;
        }

        /// <summary>
        /// 创建信息
        /// </summary>
        private void CreateServiceInfo()
        {
            CSP.Model.CSP.ServiceInfo serviceInfo = GetAddingServiceInfoByUI();
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            using (IServiceInfoBll serviceInfoBll = bllFactory.GetServiceInfoBll())
            {
                try
                {
                   serviceInfo= serviceInfoBll.CreateServiceInfo(serviceInfo);
                }
                catch (Exception ex)
                {
                    LoggerProvider.Error(ex);
                    this.FailRedirect("提交未失败", "/MyHome/ServiceInfo/List.aspx");
                }
            }

            Response.Redirect("~/MyHome/ServiceInfo/PublishOK.aspx?id=" + serviceInfo.id.ToString());
        }

        /// <summary>
        /// 根据UI获取需要添加的ServiceInfo
        /// </summary>
        /// <returns></returns>
        private CSP.Model.CSP.ServiceInfo GetAddingServiceInfoByUI()
        {
            //控件中图片发布
            this.U_ImageUpload.ReleaseImg();
            this.U_CSPEditor.ReleaseImg();
            CSP.Model.CSP.ServiceInfo serviceInfo = new Model.CSP.ServiceInfo();

            serviceInfo.username = UserProvider.UserName;
            serviceInfo.title = Txt_Title.Value;
            serviceInfo.Description = Txt_Description.Value;
            serviceInfo.ServiceInfoServiceTypeRels = new ServiceInfoServiceTypeRel[] { new ServiceInfoServiceTypeRel { 
                ServiceTypeId=Convert.ToInt32(this.Server.UrlDecode(Request["InfoType"]).Split(',')[2].Split('|')[1])
                } };
            //ServiceTypeId = Convert.ToInt32(this.Server.UrlDecode(Request["InfoType"]).Split(',')[2].Split('|')[1]),
            serviceInfo.PriceType = Convert.ToInt32(this.S_PriceType.Value);
            serviceInfo.PriceStart =  Convert.ToDecimal(this.Txt_PriceStart.Value);
            serviceInfo.PriceEnd =  Convert.ToDecimal(this.Txt_PriceEnd.Value);
            serviceInfo.Price = Convert.ToDecimal(Txt_Price.Value);
            serviceInfo.PriceUnitId = Convert.ToInt32(S_PriceUnit.Value);
            serviceInfo.OriginalPrice = Convert.ToDecimal(Txt_OriginalPrice.Value);
            serviceInfo.OriginalPriceUnitld = serviceInfo.PriceUnitId;//Convert.ToInt32(S_OriginalPriceUnit.Value);
            serviceInfo.ServiceInfoAddressRels = new ServiceInfoAddressRel[] { new ServiceInfoAddressRel { 
                    AddressId=Convert.ToInt32(this.R_Address.SelectedValue)
                } };
            //AddressId = Convert.ToInt32(this.R_Address.SelectedValue),
            serviceInfo.ClassOfMemberNumber = Convert.ToInt32(Txt_ClassOfMemberNumber.Value);
            serviceInfo.AgeStart = AgeStart.Value;
            serviceInfo.AgeEnd = Convert.ToInt32(AgeEnd.Value);
            serviceInfo.ClassTypeId = Convert.ToInt32(S_ClassType.Value);
            serviceInfo.ClassValidityStart = Convert.ToDateTime(Txt_ClassValidityStart.Text);
            serviceInfo.ClassValidityEnd = Convert.ToDateTime(Txt_ClassValidityEnd.Text);
            serviceInfo.EnjoyCount = Convert.ToInt32(Txt_EnjoyCount.Value);
            serviceInfo.KeyWords = Txt_KeyWords.Value;
            serviceInfo.Content = U_CSPEditor.Text;
            serviceInfo.img = U_CSPEditor.ImageURL;
            serviceInfo.status = (byte)Convert.ToInt32(R_Status.SelectedValue);
            serviceInfo.ServiceImages = GetServiceImages();
            serviceInfo.OnLineTime = GetOnlineTime();
            serviceInfo.CreateTime = DateTime.Now;


            return serviceInfo;
        }

        private ServiceImage[] GetServiceImages()
        {
            List<ServiceImage> imgs = new List<ServiceImage>();

            for (int i = 0; i < this.U_ImageUpload.NewImageURLs.Length; i++)
            {
                int index = this.U_ImageUpload.NewImageURLs[i].LastIndexOf("/");
                string path = this.U_ImageUpload.NewImageURLs[i].Substring(0, index + 1);
                string fileName = this.U_ImageUpload.NewImageURLs[i].Substring(index + 1);
                //this.U_ImageUpload.NewImageURLs=;
                imgs.Add(new ServiceImage
                {
                    Name = "",
                    FileName = fileName,
                    FilePath = path,
                    OrderId = this.U_ImageUpload.GetOrderId(path + fileName),

                });
            }

            return imgs.ToArray();
        }

        private DateTime? GetOnlineTime()
        {
            if (Convert.ToInt32(R_Status.SelectedValue) == (int)ServiceInfoStatus.OnLine)
            {
                return DateTime.Now;
            }
            return null;
        }


        protected void Btn_Submit_Click(object sender, EventArgs e)
        {
            CreateServiceInfo();
        }
    }
}